<?php

if(!defined('PATH')) exit();

class Houses extends Controller {

	protected $default_action = 'search';

	public $_title = 'Houses';

	public function __construct() {
		parent::__construct();
	}

	public function action_search() {
		$view = new View('houses/search_form');
		$view->render();
	}

	public function action_show() {
		if (isset($this->paramsURI[2])) {
			$this->_title = 'View House';
			$query = $this->db->query('SELECT * FROM `houses` WHERE `id` = '.$this->db->quote($this->paramsURI[2]))->fetch();
			if ($query) {
				$view = new View('houses/show');
				$view->query = $query;
				$view->render();
			} else {
				$this->archez->showMsg('House doesn\'t exist, <a href="' . PATH . '/houses/'.$this->default_action.'">click here</a> to go back', 'error');
			}
		} else {
			$this->redirect(PATH.'/houses/'.$this->default_action.'');
		}
	}

	public function action_list() {
		if (isset($_POST)) {
			if (!isset($_POST['town']) || !isset($_POST['status']) || !isset($_POST['type']) || !isset($_POST['order'])) {
				$this->archez->showMsg('You must fill whole fields, <a href="' . PATH . '/houses/'.$this->default_action.'/">click here</a> to go back.', 'error');
				return;
			}
			if (!isset($this->config['server']['towns'][$_POST['town']])) {
				$this->archez->showMsg('You must fill whole fields, <a href="' . PATH . '/houses/'.$this->default_action.'/">click here</a> to go back.', 'error');
				return;
			}
			if (!in_array($_POST['status'], array(1,2,3))) {
				$this->archez->showMsg('You must fill whole fields, <a href="' . PATH . '/houses/'.$this->default_action.'/">click here</a> to go back.', 'error');
				return;
			}
			if (!in_array($_POST['type'], array(1,2))) {
				$this->archez->showMsg('You must fill whole fields, <a href="' . PATH . '/houses/'.$this->default_action.'/">click here</a> to go back.', 'error');
				return;
			}
			if (!in_array($_POST['order'], array(1,2,3))) {
				$this->archez->showMsg('You must fill whole fields, <a href="' . PATH . '/houses/'.$this->default_action.'/">click here</a> to go back.', 'error');
				return;
			}

			$order = '`name`';
			$guild = 0;
			$status = '';
			$town = $_POST['town'];

			if ($_POST['type'] == 2)
				$guild = 1;

			if ($_POST['status'] == 2)
				$status = ' AND `owner` = 0 ';
			else if ($_POST['status'] == 3)
				$status = ' AND `owner` != 0 ';

			if ($_POST['order'] == 2)
				$order = '`size`';
			else if ($_POST['order'] == 3)
				$order = '`rent`';

			$query = $this->db->query('SELECT `id`, `name`, `price`, `owner`, `rent`, `size`, `guild` FROM `houses` WHERE `town` = '.$town.' AND `guild` = '. $guild.$status.' ORDER BY '. $order);

			$view = new View('houses/list');
			$view->query = $query;
			$this->guild = $guild;
			$view->render();
		} else {
			$this->archez->showMsg('You must fill whole fields, <a href="' . PATH . '/houses/'.$this->default_action.'/">click here</a> to go back.', 'error');
		}
	}
}
?>